package com.ryder.wx.handler;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 描述: 微信消息处理工厂
 *
 * @author Ryder
 * @version 1.0
 * @since 1.0 // 版本号，指明从哪个版本开始
 * 更新日期: 2025/02/24
 */
@Component
public class WxChatMsgFactory implements InitializingBean {

    @Autowired
    private List<WxChatMsgHandler> wxChatMsgHandlerList; // 会将所有实现WxChatMsgHandler接口的类都注入到wxChatMsgHandler中

    private Map<WxChatMsgTypeEnum, WxChatMsgHandler> handlerMap = new HashMap<>();

    /**
     * 根据消息类型获取对应的处理类
     * @param msgType 消息类型
     * @return 处理类
     */
    public WxChatMsgHandler getHandlerByMsgType(String msgType) {
        WxChatMsgTypeEnum msgTypeEnum =  WxChatMsgTypeEnum.getByMsgType(msgType);
        return handlerMap.get(msgTypeEnum);
    }

    /**
     * 初始化handlerMap 将所有实现WxChatMsgHandler接口的类都注入到wxChatMsgHandler中
     * @throws Exception 抛出异常
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        for (WxChatMsgHandler wxChatMsgHandler : wxChatMsgHandlerList) {
            handlerMap.put(wxChatMsgHandler.getMsgType(), wxChatMsgHandler);
        }
    }
}